<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.2" />






<meta name="description" content="1. HTML5 之前的存储方式1.1.Cookies作为一个前端和 Cookie 打交道的次数肯定不会少了，Cookie 算是比较古老的技术了。1993 年，网景公司雇员 Lou Montulli 为了让用户在访问某网站时，进一步提高访问速度，同时也为了进一步实现个人化网络，发明了今天广泛使用的 Cookie。 1.1.1. Cookie 的特点 Cookie 的大小受限制，Cookie 大小被">
<meta property="og:type" content="article">
<meta property="og:title" content="HTML5 之 WebStorage™">
<meta property="og:url" content="http://xiezixi.oschina.io/2018/06/01/HTML5-WebStorage/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="1. HTML5 之前的存储方式1.1.Cookies作为一个前端和 Cookie 打交道的次数肯定不会少了，Cookie 算是比较古老的技术了。1993 年，网景公司雇员 Lou Montulli 为了让用户在访问某网站时，进一步提高访问速度，同时也为了进一步实现个人化网络，发明了今天广泛使用的 Cookie。 1.1.1. Cookie 的特点 Cookie 的大小受限制，Cookie 大小被">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://xiezixi.oschina.io/blog/images/客户端查看webStorage.png">
<meta property="og:updated_time" content="2018-06-01T08:45:17.645Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="HTML5 之 WebStorage™">
<meta name="twitter:description" content="1. HTML5 之前的存储方式1.1.Cookies作为一个前端和 Cookie 打交道的次数肯定不会少了，Cookie 算是比较古老的技术了。1993 年，网景公司雇员 Lou Montulli 为了让用户在访问某网站时，进一步提高访问速度，同时也为了进一步实现个人化网络，发明了今天广泛使用的 Cookie。 1.1.1. Cookie 的特点 Cookie 的大小受限制，Cookie 大小被">
<meta name="twitter:image" content="http://xiezixi.oschina.io/blog/images/客户端查看webStorage.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://xiezixi.oschina.io/2018/06/01/HTML5-WebStorage/"/>





  <title>HTML5 之 WebStorage™ | 个人博客</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">曦瓜皮</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>


 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://xiezixi.oschina.io/blog/2018/06/01/HTML5-WebStorage/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="曦瓜皮">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">HTML5 之 WebStorage™</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-01T16:45:17+08:00">
                2018-06-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/HTML5/" itemprop="url" rel="index">
                    <span itemprop="name">HTML5</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="1-HTML5-之前的存储方式"><a href="#1-HTML5-之前的存储方式" class="headerlink" title="1. HTML5 之前的存储方式"></a>1. HTML5 之前的存储方式</h2><h3 id="1-1-Cookies"><a href="#1-1-Cookies" class="headerlink" title="1.1.Cookies"></a>1.1.Cookies</h3><p>作为一个前端和 Cookie 打交道的次数肯定不会少了，Cookie 算是比较古老的技术了。1993 年，网景公司雇员 Lou Montulli 为了让用户在访问某网站时，进一步提高访问速度，同时也为了进一步实现个人化网络，发明了今天广泛使用的 Cookie。</p>
<h4 id="1-1-1-Cookie-的特点"><a href="#1-1-1-Cookie-的特点" class="headerlink" title="1.1.1. Cookie 的特点"></a>1.1.1. Cookie 的特点</h4><ol>
<li>Cookie 的大小受限制，Cookie 大小被限制在4KB，不能接受像大文件或邮件那样的大数据；</li>
<li>只要有请求涉及 Cookie，Cookie 就要在服务器和浏览器之间来回传送。而且 Cookie 数据始终在同源的 HTTP 请求中携带（即使不需要），这也是 Cookie 不能太大的重要原因。正统的 Cookie 分发是通过扩展 HTTP 协议来实现的，服务器通过在 HTTP 的响应头中加上一行特殊的指示以提示浏览器按照指示生成相应的 Cookie；</li>
<li>Cookie 的内容主要包括：名字，值，过期时间，路径和域。路径与域一起构成 Cookie 的作用范围。若不设置过期时间，则表示这个 Cookie 的生命期为浏览器会话期间，关闭浏览器窗口，Cookie 就消失。这种生命期为浏览器会话期的 Cookie 被称为会话 Cookie。会话 Cookie 一般不存储在硬盘上而是保存在内存里，当然这种行为并不是规范规定的。若设置了过期时间，浏览器就会把 Cookie 保存到硬盘上，关闭后再次打开浏览器，这些 Cookie 仍然有效直到超过设定的过期时间。存储在硬盘上的 Cookie 可以在不同的浏览器进程间共享，比如两个IE窗口。而对于保存在内存里的 Cookie，不同的浏览器有不同的处理方式。</li>
</ol>
<h4 id="1-1-2-document-cookie-的属性"><a href="#1-1-2-document-cookie-的属性" class="headerlink" title="1.1.2. document.cookie 的属性"></a>1.1.2. document.cookie 的属性</h4><p><strong> expires属性 </strong></p>
<blockquote>
<p>指定了 Cookie 的生存期，默认情况下 Cookie 是暂时存在的，他们存储的值只在浏览器会话期间存在，当用户推出浏览器后这些值也会丢失，如果想让 Cookie 存在一段时间，就要为 expires 属性设置为未来的一个过期日期。现在已经被 max-age 属性所取代，max-age 用秒来设置 Cookie 的生存期。</p>
</blockquote>
<p><strong> path属性 </strong></p>
<blockquote>
<p>它指定与 Cookie 关联在一起的网页。在默认的情况下 Cookie 会与创建它的网页，该网页处于同一目录下的网页以及与这个网页所在目录下的子目录下的网页关联。</p>
</blockquote>
<p><strong> domain属性 </strong></p>
<blockquote>
<p>domain 属性可以使多个 web 服务器共享 cookie。domain 属性的默认值是创建 cookie 的网页所在服务器的主机名。不能将一个 cookie 的域设置成服务器所在的域之外的域。例如让位于<code>order.damonare.cn</code>的服务器能够读取<code>catalog.damonare.cn</code>设置的 cookie 值。如果<code>catalog.damonare.cn</code>的页面创建的 cookie 把自己的 path 属性设置为<code>/</code>，把 domain 属性设置成<code>.damonare.cn</code>，那么所有位于<code>catalog.damonare.cn</code>的网页和所有位于<code>orlders.damonare.cn</code>的网页，以及位于<code>damonare.cn</code>域的其他服务器上的网页都可以访问这个  cookie。</p>
</blockquote>
<p><strong> secure属性 </strong></p>
<blockquote>
<p>它是一个布尔值，指定在网络上如何传输 cookie，默认是不安全的，通过一个普通的 http 连接传输</p>
</blockquote>
<h4 id="1-1-3-优秀开源框架"><a href="#1-1-3-优秀开源框架" class="headerlink" title="1.1.3. 优秀开源框架"></a>1.1.3. 优秀开源框架</h4><p><a href="https://github.com/js-cookie/js-cookie" target="_blank" rel="noopener">js-cookie</a>，<a href="https://github.com/carhartl/jquery-cookie" target="_blank" rel="noopener">jquery-cookie</a>。</p>
<h3 id="1-2-UserData"><a href="#1-2-UserData" class="headerlink" title="1.2. UserData"></a>1.2. UserData</h3><p>仅 IE 支持，容量为 64KB。</p>
<h3 id="1-3-Flash"><a href="#1-3-Flash" class="headerlink" title="1.3. Flash"></a>1.3. Flash</h3><p>100KB，非 HTML 原生，需要插件支持。</p>
<h3 id="1-4-Google-Gears-SQLite"><a href="#1-4-Google-Gears-SQLite" class="headerlink" title="1.4. Google Gears SQLite"></a>1.4. Google Gears SQLite</h3><p>需要插件支持，容量无限制。</p>
<h2 id="2-localStorage"><a href="#2-localStorage" class="headerlink" title="2. localStorage"></a>2. localStorage</h2><h3 id="2-1-什么是-localStorage"><a href="#2-1-什么是-localStorage" class="headerlink" title="2.1. 什么是 localStorage"></a>2.1. 什么是 localStorage</h3><p>localStorage 为标准的键值对（Key-Value,简称KV）数据类型，简单但也易扩展，只要以某种编码方式把想要存储进 localStorage 的对象给转化成字符串，就能轻松支持。举点例子：把对象转换成 json 字符串，就能让存储对象了；把图片转换成 DataUrl（base64），就可以存储图片了。另外对于键值对数据类型来说，“键是唯一的”这个特性也是相当重要的，重复以同一个键来赋值的话，会覆盖上次的值。底层数据接口是 sqlite，按域名将数据分别保存到对应数据库文件里。它能保存更大的数据（IE8 上是 10MB，Chrome 是5 MB），同时保存的数据不会再发送给服务器，避免带宽浪费。</p>
<h3 id="2-2-localStorage-特点"><a href="#2-2-localStorage-特点" class="headerlink" title="2.2. localStorage 特点"></a>2.2. localStorage 特点</h3><p>localStorage 理论上来说是永久有效的，即不主动清空的话就不会消失，即使保存的数据超出了浏览器所规定的大小，也不会把旧数据清空而只会报错。但需要注意的是，在移动设备上的浏览器或各 Native App 用到的 WebView 里，localStorage 都是不可靠的，可能会因为各种原因（比如说退出 App、网络切换、内存不足等原因）被清空。</p>
<p>localStorage 原生是不支持设置过期时间的，想要设置的话，就只能自己来封装一层逻辑来实现：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">set</span>(<span class="params">key, value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> curTime = <span class="keyword">new</span> <span class="built_in">Date</span>().getTime();<span class="comment">//获取当前时间</span></span><br><span class="line">    localStorage.setItem(key, <span class="built_in">JSON</span>.stringify(&#123;<span class="attr">val</span>: value, <span class="attr">time</span>: curTime&#125;));<span class="comment">//转换成json字符串序列</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">get</span>(<span class="params">key, exp</span>)//<span class="title">exp</span>是设置的过期时间</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">var</span> val = localStorage.getItem(key);<span class="comment">//获取存储的元素</span></span><br><span class="line">    <span class="keyword">var</span> dataObj = <span class="built_in">JSON</span>.parse(val);<span class="comment">//解析出json对象</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">new</span> <span class="built_in">Date</span>().getTime() - dataObj.time &gt; exp)<span class="comment">//如果当前时间-减去存储的元素在创建时候设置的时间 &gt; 过期时间</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">"expires"</span>);<span class="comment">//提示过期</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">"val="</span> + dataObj.val);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-3-localStorage-的属性方法"><a href="#2-3-localStorage-的属性方法" class="headerlink" title="2.3. localStorage 的属性方法"></a>2.3. localStorage 的属性方法</h3><table>
<thead>
<tr>
<th>属性方法</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>localStorage.length</code></td>
<td>获得 storage 中的个数</td>
</tr>
<tr>
<td><code>localStorage.key(n)</code></td>
<td>获得 storage 中第 n 个元素对的键值（第一个元素是 0）</td>
</tr>
<tr>
<td><code>localStorage.getItem(key)</code></td>
<td>获取键值 key 对应的值</td>
</tr>
<tr>
<td><code>localStorage.setItem(key, value)</code></td>
<td>添加数据，键值为 key，值为 value</td>
</tr>
<tr>
<td><code>localStorage.removeItem(key)</code></td>
<td>移除键值为 key 的数据</td>
</tr>
<tr>
<td><code>localStorage.clear()</code></td>
<td>清除所有数据</td>
</tr>
</tbody>
</table>
<h3 id="2-4-localStorage-的缺点"><a href="#2-4-localStorage-的缺点" class="headerlink" title="2.4. localStorage 的缺点"></a>2.4. localStorage 的缺点</h3><ul>
<li>localStorage 大小有限制，各个浏览器不一致</li>
<li>localStorage 在隐私模式下不可读取</li>
<li>localStorage 本质是在读写文件，数据多的话会比较卡</li>
<li>localStorage 不能被爬虫爬取，不要用它完全取代 URL 传参</li>
<li>WebStorage 固然简单实用，但是数据的明文存储实在是硬伤</li>
</ul>
<h3 id="2-5-兼容性情况"><a href="#2-5-兼容性情况" class="headerlink" title="2.5. 兼容性情况"></a>2.5. 兼容性情况</h3><p><a href="https://caniuse.com/#search=webstorage" target="_blank" rel="noopener">webStroage兼容性情况</a></p>
<h2 id="3-sessionStorage"><a href="#3-sessionStorage" class="headerlink" title="3. sessionStorage"></a>3. sessionStorage</h2><h3 id="3-1-sessionStorage-的特点"><a href="#3-1-sessionStorage-的特点" class="headerlink" title="3.1. sessionStorage 的特点"></a>3.1. sessionStorage 的特点</h3><p>和服务器端使用的 session 类似，是一种会话级别的缓存，关闭浏览器会数据会被清除。不过有点特别的是它的作用域是窗口级别的，也就是说不同窗口间的 sessionStorage 数据不能共享的。</p>
<h3 id="3-2-sessionStorage-的属性方法"><a href="#3-2-sessionStorage-的属性方法" class="headerlink" title="3.2. sessionStorage 的属性方法"></a>3.2. sessionStorage 的属性方法</h3><p>使用方法（和 localStorage 完全相同）：</p>
<table>
<thead>
<tr>
<th>属性方法</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>sessionStorage.length</code></td>
<td>获得 storage 中的个数</td>
</tr>
<tr>
<td><code>sessionStorage.key(n)</code></td>
<td>获得 storage 中第 n 个元素对的键值（第一个元素是 0）</td>
</tr>
<tr>
<td><code>sessionStorage.getItem(key)</code></td>
<td>获取键值 key 对应的值</td>
</tr>
<tr>
<td><code>sessionStorage.setItem(key, value)</code></td>
<td>添加数据，键值为 key，值为 value</td>
</tr>
<tr>
<td><code>sessionStorage.removeItem(key)</code></td>
<td>移除键值为 key 的数据</td>
</tr>
<tr>
<td><code>sessionStorage.clear()</code></td>
<td>清除所有数据</td>
</tr>
</tbody>
</table>
<h2 id="4-webStorage-事件监测"><a href="#4-webStorage-事件监测" class="headerlink" title="4. webStorage 事件监测"></a>4. webStorage 事件监测</h2><p>在HTML5中，可以通 过 window 对象的 storage 事件进行监听。当存储的 storage 数据发生变化时都会触发它,也就是说当前页面的 storage 改变的时候,触发这个事件也会触发调用所有同域下其他窗口的 storage 事件。但要注意：该事件不会在导致数据变化的当前页面触发。</p>
<p><strong>使用<code>addEventListener</code>进行监听</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">'storage'</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">//当sessionStorage或localStorage中的值发生变动时所要执行的处理</span></span><br><span class="line">&#125;,<span class="literal">false</span>);</span><br></pre></td></tr></table></figure>
<p>在事件处理函数中，触发事件的事件对象（event 参数值）有以下属性：</p>
<table>
<thead>
<tr>
<th>属性方法</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>event.key</code></td>
<td>被修改的数据键值</td>
</tr>
<tr>
<td><code>event.oldValue</code></td>
<td>被修改前的值</td>
</tr>
<tr>
<td><code>event.newValue</code></td>
<td>被修改后的值</td>
</tr>
<tr>
<td><code>event.url</code></td>
<td>页面URL地址</td>
</tr>
<tr>
<td><code>event.storageArea</code></td>
<td>变动的 sessionStorage 对象或 localStorage对象</td>
</tr>
<tr>
<td><code>sessionStorage.clear()</code></td>
<td>清除所有数据</td>
</tr>
</tbody>
</table>
<h2 id="5-webStorage-和-cookie-的区别"><a href="#5-webStorage-和-cookie-的区别" class="headerlink" title="5. webStorage 和 cookie 的区别"></a>5. webStorage 和 cookie 的区别</h2><p><strong>localStorage 和 sessionStorage 的区别主要是在于其生存期</strong></p>
<ul>
<li><p>sessionStorage 用于本地存储一个会话（session）中的数据，这些数据只有在同一个会话中的页面才能访问并且当会话结束后数据也随之销毁。因此sessionStorage不是一种持久化的本地存储，仅仅是会话级别的存储。当用户关闭浏览器窗口后，数据立马会被删除。</p>
</li>
<li><p>localStorage 用于持久化的本地存储，除非主动删除数据，否则数据是永远不会过期的。第二天、第二周或下一年之后，数据依然可用。</p>
</li>
</ul>
<p><strong>webStorage 和 cookie 的区别</strong></p>
<ul>
<li>WebStorage（localStorage 和 sessionStorage）的概念和 cookie 相似，区别是它是为了更大容量存储设计的。Cookie 的大小是受限的，并且每次你请求一个新的页面的时候 Cookie 都会被发送过去，这样无形中浪费了带宽，另外cookie还需要指定作用域，不可以跨域调用。</li>
<li>除此之外，WebStorage 拥有 setItem, getItem, removeItem, clear等方法，不像 cookie 需要前端开发者自己封装 setCookie，getCookie。</li>
<li>但是 Cookie 也是不可以或缺的：Cookie 的作用是与服务器进行交互，作为 HTTP 规范的一部分而存在 ，而 WebStorage 仅仅是为了在本地“存储”数据而生。</li>
</ul>
<h2 id="6-网页皮肤实例"><a href="#6-网页皮肤实例" class="headerlink" title="6. 网页皮肤实例"></a>6. 网页皮肤实例</h2><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"utf-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>网页皮肤<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">section</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">"pink-btn"</span>&gt;</span>粉色<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">"green-btn"</span>&gt;</span>绿色<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">"brown-btn"</span>&gt;</span>卡其<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">section</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"colorDiv"</span> <span class="attr">style</span>=<span class="string">"width: 500px;height: 500px;border: 1px solid #ccc;background-color: white;"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- javascript部分 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="javascript">    <span class="comment">//首先检测浏览器是否支持</span></span></span><br><span class="line"><span class="javascript">    <span class="keyword">if</span> (<span class="built_in">window</span>.localStorage) &#123;</span></span><br><span class="line"><span class="javascript">        <span class="built_in">console</span>.log(<span class="string">"浏览器支持localStorage"</span>);</span></span><br><span class="line"><span class="javascript">    &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="javascript">        <span class="built_in">console</span>.log(<span class="string">"浏览器不支持localStorage"</span>);</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">    <span class="comment">//事件监听</span></span></span><br><span class="line"><span class="javascript">    <span class="keyword">var</span> EventUtil = &#123;</span></span><br><span class="line"><span class="javascript">        addEvent: <span class="function"><span class="keyword">function</span> (<span class="params">event, type, handler</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="keyword">if</span> (event.addEventListener) &#123;</span></span><br><span class="line"><span class="javascript">                event.addEventListener(type, handler, <span class="literal">false</span>);</span></span><br><span class="line"><span class="javascript">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (event.attachEvent) &#123;</span></span><br><span class="line"><span class="javascript">                event.attachEvent(<span class="string">'on'</span> + type, handler);</span></span><br><span class="line"><span class="javascript">            &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="javascript">                event[<span class="string">'on'</span> + type] = handler;</span></span><br><span class="line"><span class="undefined">            &#125;</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">    <span class="comment">//设置选择样式和保存至localStorage</span></span></span><br><span class="line"><span class="javascript">    <span class="keyword">var</span> colorVal = <span class="string">"white"</span>;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">var</span> colorDiv = <span class="built_in">document</span>.getElementById(<span class="string">"colorDiv"</span>);</span></span><br><span class="line"><span class="javascript">    <span class="keyword">var</span> bgColor = &#123;</span></span><br><span class="line"><span class="javascript">        setColor: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            colorDiv.style.backgroundColor = <span class="built_in">window</span>.localStorage.bg;</span></span><br><span class="line"><span class="undefined">        &#125;,</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">        pinkSet: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            colorVal = <span class="string">"#FFDAB9"</span>;</span></span><br><span class="line"><span class="javascript">            <span class="built_in">window</span>.localStorage.setItem(<span class="string">"bg"</span>, colorVal);</span></span><br><span class="line"><span class="undefined">            bgColor.setColor();</span></span><br><span class="line"><span class="undefined">        &#125;,</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">        greenSet: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            colorVal = <span class="string">"#9BCD9B"</span>;</span></span><br><span class="line"><span class="javascript">            <span class="built_in">window</span>.localStorage.setItem(<span class="string">"bg"</span>, colorVal);</span></span><br><span class="line"><span class="undefined">            bgColor.setColor();</span></span><br><span class="line"><span class="undefined">        &#125;,</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">        brownSet: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            colorVal = <span class="string">"#CDC9A5"</span>;</span></span><br><span class="line"><span class="javascript">            <span class="built_in">window</span>.localStorage.setItem(<span class="string">"bg"</span>, colorVal);</span></span><br><span class="line"><span class="undefined">            bgColor.setColor();</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">    <span class="built_in">window</span>.onload = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="undefined">        bgColor.setColor();</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> btnList = <span class="built_in">document</span>.getElementsByTagName(<span class="string">"button"</span>);</span></span><br><span class="line"><span class="javascript">        EventUtil.addEvent(btnList[<span class="number">0</span>], <span class="string">'click'</span>, bgColor.pinkSet);</span></span><br><span class="line"><span class="javascript">        EventUtil.addEvent(btnList[<span class="number">1</span>], <span class="string">'click'</span>, bgColor.greenSet);</span></span><br><span class="line"><span class="javascript">        EventUtil.addEvent(btnList[<span class="number">2</span>], <span class="string">'click'</span>, bgColor.brownSet);</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="7-客户端查看-webStorage"><a href="#7-客户端查看-webStorage" class="headerlink" title="7. 客户端查看 webStorage"></a>7. 客户端查看 webStorage</h2><p><img src="http://xiezixi.oschina.io/blog/images/客户端查看webStorage.png" alt="客户端查看 webStorage"></p>
<h2 id="8-优秀开源框架"><a href="#8-优秀开源框架" class="headerlink" title="8. 优秀开源框架"></a>8. 优秀开源框架</h2><p><a href="https://github.com/marcuswestin/store.js" target="_blank" rel="noopener">store.js</a>，<a href="https://github.com/jaicab/localFont" target="_blank" rel="noopener">localFont</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/06/01/HTML5-WebSocket/" rel="next" title="HTML5 之 WebSocket™">
                <i class="fa fa-chevron-left"></i> HTML5 之 WebSocket™
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/06/01/HTML5-SSE/" rel="prev" title="HTML5 之 Server-Sent Events™">
                HTML5 之 Server-Sent Events™ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/avatar.jpg"
               alt="曦瓜皮" />
          <p class="site-author-name" itemprop="name">曦瓜皮</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives/">
                <span class="site-state-item-count">15</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories/index.html">
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        

      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-HTML5-之前的存储方式"><span class="nav-number">1.</span> <span class="nav-text">1. HTML5 之前的存储方式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-Cookies"><span class="nav-number">1.1.</span> <span class="nav-text">1.1.Cookies</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-1-Cookie-的特点"><span class="nav-number">1.1.1.</span> <span class="nav-text">1.1.1. Cookie 的特点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-2-document-cookie-的属性"><span class="nav-number">1.1.2.</span> <span class="nav-text">1.1.2. document.cookie 的属性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-3-优秀开源框架"><span class="nav-number">1.1.3.</span> <span class="nav-text">1.1.3. 优秀开源框架</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-UserData"><span class="nav-number">1.2.</span> <span class="nav-text">1.2. UserData</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-Flash"><span class="nav-number">1.3.</span> <span class="nav-text">1.3. Flash</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-4-Google-Gears-SQLite"><span class="nav-number">1.4.</span> <span class="nav-text">1.4. Google Gears SQLite</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-localStorage"><span class="nav-number">2.</span> <span class="nav-text">2. localStorage</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-什么是-localStorage"><span class="nav-number">2.1.</span> <span class="nav-text">2.1. 什么是 localStorage</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-localStorage-特点"><span class="nav-number">2.2.</span> <span class="nav-text">2.2. localStorage 特点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-localStorage-的属性方法"><span class="nav-number">2.3.</span> <span class="nav-text">2.3. localStorage 的属性方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4-localStorage-的缺点"><span class="nav-number">2.4.</span> <span class="nav-text">2.4. localStorage 的缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-5-兼容性情况"><span class="nav-number">2.5.</span> <span class="nav-text">2.5. 兼容性情况</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-sessionStorage"><span class="nav-number">3.</span> <span class="nav-text">3. sessionStorage</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-sessionStorage-的特点"><span class="nav-number">3.1.</span> <span class="nav-text">3.1. sessionStorage 的特点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-sessionStorage-的属性方法"><span class="nav-number">3.2.</span> <span class="nav-text">3.2. sessionStorage 的属性方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-webStorage-事件监测"><span class="nav-number">4.</span> <span class="nav-text">4. webStorage 事件监测</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-webStorage-和-cookie-的区别"><span class="nav-number">5.</span> <span class="nav-text">5. webStorage 和 cookie 的区别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-网页皮肤实例"><span class="nav-number">6.</span> <span class="nav-text">6. 网页皮肤实例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-客户端查看-webStorage"><span class="nav-number">7.</span> <span class="nav-text">7. 客户端查看 webStorage</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-优秀开源框架"><span class="nav-number">8.</span> <span class="nav-text">8. 优秀开源框架</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">曦瓜皮</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  





  

  

  

  

  

  

</body>
</html>
